<link href="/css/style.css" rel="stylesheet">
<link href="/css/style-responsive.css" rel="stylesheet">
<link href="/js/advanced-datatable/css/demo_page.css" rel="stylesheet" />
<link href="/js/advanced-datatable/css/demo_table.css" rel="stylesheet" />
<link rel="stylesheet" href="/js/data-tables/DT_bootstrap.css" />
<link href="/css/style.css" rel="stylesheet">
<link href="/css/style-responsive.css" rel="stylesheet">

<body class="panel" style="padding: 0;">
	<div class="row">
		<div class="col-sm-12">
			<div class="panel-body">
				<header class="panel-heading" style="height: 50;">
					<div class="col-md-10">API地址列表&nbsp;&nbsp;(被授权的访问者可以凭借token使用以下API)</div>
					<div class="col-md-2" align="right"><button data-toggle="modal" href="#myModal" class="btn btn-success  btn-sm" onclick="currentAppId = 0;clearForm();">新增API</button>
					</div>
				</header>
				<div class="adv-table ">
					<table class="  table " id="listTable" width="100%">
						<thead>
							<tr>
								<th width="10">ID</th>
								<th width="20">api 名称</th>
								<th width="25">url</th>
								<th width="35">描述</th> 
								<th width="10"> </th>
							</tr>
						</thead>

						<tbody id="maintablebody">
						</tbody>
					</table>
				</div>
				<footer>
					<label>
						<select class="form-control" id="stepInput" onchange="currentPage = 1;changeStep(false)" size="1" name="hidden-table-info_length" aria-controls="hidden-table-info">
						<option value="10" selected="selected">10</option>
						<option value="25">25</option>
						<option value="50">50</option>
						<option value="100">100</option>
					</select> records per page</label>

					<div id="pageLabelDiv" class="dataTables_paginate paging_bootstrap pagination">
						<ul>
						</ul>
					</div>
				</footer>
			</div>

		</div>
		<!--	//-----------弹出创建api url 的窗口------start------------>
		<div class="modal fade" id="myModal" tabindex="-100" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
						<h4 class="modal-title" id="addAPIUserTitle">添加API</h4>
					</div>

					<div class="modal-body row">
						<div class="col-md-4">
							<div class="form-group">
								<label>api名称</label>
								<input type="text" class="form-control" id="label" />
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label> 描述</label>
								<input type="text" class="form-control" id="description" />
							</div>
						</div>
						<div class="col-md-2">
							<div class="form-group">
								<label>启用</label> <br />
								<input type="checkbox" id="apiEnable" name="apiEnable" checked />
							</div>
						</div>
					</div>

					<div class="modal-body row">

						<div class="col-md-12">
							<div class="form-group">
								<label>url</label>
								<input type="text" class="form-control" id="url" />
							</div>
						</div>
					</div>

					<div class="modal-body row">
						<div class="col-md-5">

						</div>
						<div class="col-md-2">
							<button class="btn btn-success  btn-sm" onclick="saveNewitem()">保存</button>
						</div>
						<div class="col-md-5">

						</div>
					</div>
				</div>
			</div>
		</div>
		<!--   //-----------弹出创建api url的窗口------end----------      -->

		<!--	//-----------弹出设置 api 的访问账户的窗口------start------------>
		<div class="modal fade" id="setApiUserModal" tabindex="-200" role="dialog" aria-labelledby="setApiUserLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
						<h4 class="modal-title">设置该API的访问账户</h4>
					</div>
					<div class="modal-body row" >
<div class="col-md-12" id="allApiUserSelector">

						</div>
					</div>
					<div class="modal-body row">
						<div class="col-md-5">

						</div>
						<div class="col-md-2">
							<button class="btn btn-success  btn-sm" onclick="saveApiUserUrl()">保存</button>
						</div>
						<div class="col-md-5">

						</div>
					</div>
				</div>
			</div>
		</div>
		<!--   //-----------弹出设置 api 的访问账户的窗口------end----------      -->
		<!-- Placed js at the end of the document so the pages load faster -->
		<script src="/js/jquery-1.10.2.min.js"></script>
		<script src="/js/jquery-ui-1.9.2.custom.min.js"></script>
		<script src="/js/jquery-migrate-1.2.1.min.js"></script>
		<script src="/js/bootstrap.min.js"></script>
		<script src="/js/modernizr.min.js"></script>
		<script src="/js/jquery.nicescroll.js"></script>
		<!--common scripts for all pages-->
		<script src="/js/scripts.js"></script>
		<script src="/js/html5shiv.js"></script>
		<script src="/js/respond.min.js"></script>

		<script>
			var totalCount = 0
			var currentPage = 1
			var step = 10
			var currentId = 0
			var tablebody
			var currentListData
			var adddata
			var host
			var userWithPirvilege
			var currentApiId = -1
				//从API获取数据列表
			function getList(page, tempstep) {
				currentPage = page;
				step = tempstep
				$.get(host + "/list_api_url/" + currentPage + "/step/" + step, null, listToSuccess, "json");
			}
			//页面载入后先获取默认条数的数据
			window.onload = function() {
					host = "http://" + window.location.host
					getList(currentPage, step);
				}
				//从数据库中获取列表成功
			function listToSuccess(response, status, xhr) {

				if(status == "success" && response.reusltCode == "200") {
					currentListData = response.reusltDetail.apiUrllist;
					userWithPirvilege = response.reusltTitle;
					totalCount = response.totalCount;
					clearDataTable();
					changeStep(true);
					fillTable();
					getApiUserList();
				} else {
					alert(response);
				}

			}
 function onBodyResize() { 
 
		}
			function getApiUserList() {
				$.get(host + "/list_api_user/1/step/10000", null, listApiuserToSuccess, "json");
			}
			var apiuserList
			var apiUserSelect
			var apiUserUrlList

			function listApiuserToSuccess(response, status, xhr) {

				if(status == "success" && response.reusltCode == "200") {
					apiuserList = response.reusltDetail.apiuserlist;
					apiUserUrlList = response.reusltDetail.apiuserurl;
					clearApiuserTable();
					parent.setMainContentHeight(apiuserList.length,50);  
				} else {
					alert(response);
				}

			}
			//清空api user 选择栏
			function clearApiuserTable() {
				apiUserSelect = document.getElementById("allApiUserSelector");

			}

			//采用本地数组中的数据填充表格
			function fillTable() {
				adddata = "";
				$.each(currentListData, function(index, item) {
					adddata += ("<tr ");

					var start_s = "<u><s>";
					var end_s = "</s></u>";
					if(item.enable == 1) {
						start_s = "";
						end_s = "";
					}
					adddata += ("  name=" + index + ">");
					adddata += ("<td>" + start_s + item.id + end_s + "</td>");
					adddata += ("<td>" + start_s + item.label + end_s + "</td>"); 
					adddata += ("<td>" + start_s + item.url + end_s + "</td>");
					adddata += ("<td >" + start_s + item.description + end_s + "</td>");
					if(userWithPirvilege.is_manager == true) {
						adddata += ("<td align='right'> <a data-toggle='modal' href='#myModal'  class='tn btn-success btn-sm' onclick='editAppItem(" + index + ")' >编辑</a> <a data-toggle='modal' href='#setApiUserModal'  class='tn btn-warning btn-sm' onclick='setAPIUser(" + index + ")' >访问者</a></td>");
					}
					adddata += "</tr>";
				});
				tablebody.append(adddata);
			}
			//点击编辑按钮的时候
			function editAppItem(i) {
				//currentTabIndex = i;
				currentApiId = currentListData[i].id;
				document.getElementById("label").value = currentListData[i].label;
				document.getElementById("description").value = currentListData[i].description;
				document.getElementById("url").value = currentListData[i].url;
				if(currentListData[i].enable == 1) {
					document.getElementById("apiEnable").checked = true;
				} else {
					document.getElementById("apiEnable").checked = false;
				}
			}
			//设置可以使用这个API的账户
			function setAPIUser(i) {
				//	currentTabIndex = i;
				currentApiId = currentListData[i].id;
				addAPIUserTitle.innerText = currentListData[i].label;
				fillApiUserSelecter(currentListData[i].url);
			}
			//采用本地数组中的数据填充表格
			function fillApiUserSelecter(apiUrl) {
				var innerhtmltext = ""
				$.each(apiuserList, function(index, item) {
					innerhtmltext += '	<input type="checkbox" onchange="onselectThisUser(this,\'' + item.token + '\')" value="' + item.user_name + '"'
					var thisApiUrlUserList = apiUserUrlList[apiUrl]
					if(thisApiUrlUserList) {
						for(var i = 0; i < apiUserUrlList[apiUrl].length; i++) {

							if(item.token == apiUserUrlList[apiUrl][i]) {
								innerhtmltext += ' checked="checked" '
								break;
							}
						}
					}
					innerhtmltext += ('>' + item.user_name + '</input>');
				});

				apiUserSelect.innerHTML = innerhtmltext;
			}
			//点击编辑按钮的时候
			function saveNewitem() {
				var currentdata = new Object();
				currentdata.id = currentApiId;
				currentdata.label = document.getElementById("label").value;
				currentdata.description = document.getElementById("description").value;
				currentdata.url = document.getElementById("url").value;
				if(document.getElementById("apiEnable").checked == true) {
					currentdata.enable = 1;
				} else {
					currentdata.enable = 0;
				}
				if (currentdata.label == "") {
					document.getElementById("label").focus();
					alert("名称必填");
					return;
				}
				if (currentdata.url == "") {
					document.getElementById("url").focus();
					alert("url必填");
					return;
				}
				 
				currentdata.page = currentPage;
				currentdata.step = step;
				$.ajaxSetup({
					contentType: 'application/json'
				});
				$.post(host + "/add_api_url", JSON.stringify(currentdata), saveSuccess, "json");

			}
			//保存成功
			function saveSuccess(response, status, xhr) {
				if(status == "success" && response.reusltCode == "200") {
					listToSuccess(response, status, xhr);
					currentApiId = 0;
					$('#myModal').modal('hide');
				} else {
					alert(response);
				} 
			}
			//清空数据表格
			function clearDataTable() {
				tablebody = $("#maintablebody");
				tablebody.empty();
			}
			//清空表单
			function clearForm() {
				document.getElementById("label").value = "";
				document.getElementById("description").value = "";
				document.getElementById("url").value = "";
			}

			//每页的条数发生改变时  重新计算分页条数
			function changeStep(onlyChangeStep) {
				var pagelabelDiv = $("#pageLabelDiv ul");
				pagelabelDiv.empty();
				var stepinput = document.getElementById("stepInput")
				step = parseInt(stepinput.options[stepinput.selectedIndex].value);
				var pageNum = Math.ceil(totalCount / step);
				if(currentPage <= 1) {
					pagelabelDiv.append('<li class="prev disabled"><a href="#">← Previous</a></li>')
				} else {
					pagelabelDiv.append('<li class="prev" onclick="getList(' + (currentPage - 1) + ',' + step + ')" ><a href="#">← Previous</a></li>')
				}
				if(pageNum > 6) {
				for(var i = 1; i <= pageNum; i++) {
					if((i) == currentPage) {
						pagelabelDiv.append('<li class="active"><a   >' + (i) + '</a></li>')
					} else if((i <= 2)) {
						pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
					} else if((i >= currentPage - 1 && (i <=currentPage + 1)) || (i > pageNum - 2)) {
						pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
					}
				}

			} else {
				for(var i = 1; i <= pageNum; i++) {
					if((i) == currentPage) {
						pagelabelDiv.append('<li class="active"><a   >' + (i) + '</a></li>')
					} else {
						pagelabelDiv.append('<li onclick="getList(' + i + ',' + step + ')"><a  href="#">' + (i) + '</a></li>')
					}
				}
				}
				if(currentPage >= pageNum) {
					pagelabelDiv.append('<li class="next disabled"><a href="#">Next → </a></li>')
				} else {
					pagelabelDiv.append('<li class="next" onclick="getList(' + (currentPage + 1) + ',' + step + ')" ><a href="#">Next → </a></li>')
				}
				if(onlyChangeStep == false) {
					getList(currentPage, step);
				}
			}

			function onselectThisUser(selectUserItem, usertoken) {
				var currentUrl = ""
				for(var i = 0; i < currentListData.length; i++) {

					if(currentApiId == currentListData[i].id) {

						currentUrl = currentListData[i].url;
						break;
					}
				}
				if(selectUserItem.checked == true) {
					addApiUserUrl(usertoken, currentUrl);
				} else {
					cutApiUserUrl(usertoken, currentUrl);
				}

			}
			var addapiUserlist = new Array()

			function addApiUserUrl(usertoken, apiurl) {
				var hasThisPrivilege = false;
				if(addapiUserlist) {

					for(var j = 0; j < apiUserUrlList.length; j++) {
						var currentitem = apiUserUrlList[j];
						if(currentitem.user_token == usertoken && currentitem.api_url == apiurl) {
							hasThisPrivilege = true;
						}
					}
				} else {
					addapiUserlist = new Array();
				}
				if(hasThisPrivilege == false) {
					var newObject = new Object();
					newObject.user_token = usertoken;
					newObject.api_url = apiurl;
					newObject.enable = 1;
					newObject.id = 0;
					addapiUserlist = addapiUserlist.concat(newObject);

				}
			}
			var removeApiUserUrlList = new Array()

			function cutApiUserUrl(usertoken, apiurl) {
				if(apiUserUrlList) {
					var currentList = apiUserUrlList[apiurl];
					for(var i = 0; i < currentList.length; i++) {
						var currentitem = currentList[i]
						if(currentitem == usertoken) {
							var newObject = new Object();
							newObject.user_token = usertoken;
							newObject.api_url = apiurl;
							newObject.enable = 1;
							newObject.id = 0;
							removeApiUserUrlList = removeApiUserUrlList.concat(newObject);
							apiUserUrlList[apiurl].splice(i, 1);
						}
					}
				}
			}

			function saveApiUserUrl() {
				var currentUrl = ""

				var sendObj = new Object()
				sendObj.add_api_user_urllist = addapiUserlist;
				sendObj.cutApi_user_urllist = removeApiUserUrlList;
				$.post(host + "/api_user_url/" + currentApiId, JSON.stringify(sendObj), saveApiUserUrlSuccess, "json");
			}

			function saveApiUserUrlSuccess(response, status, xhr) {
				if(status == "success" && response.reusltCode == "200") {
					apiUserUrlList = response.reusltDetail;
					removeApiUserUrlList = new Array();
					addapiUserlist = new Array();
					$('#setApiUserModal').modal('hide');
					alert("保存成功");
				} else {
					alert(response);
				}

			}
		</script>

</body>